package com.red.star.wechat.work.site.banner;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.red.star.wechat.data.entity.*;
import com.red.star.wechat.data.entity.vo.MallBannerDataVo;
import com.red.star.wechat.data.mappers.BannerMallMapper;
import com.red.star.wechat.data.mappers.BannerMapper;
import com.red.star.wechat.data.mappers.MallMapper;
import com.red.star.wechat.data.utils.CheckUtil;
import com.red.star.wechat.data.utils.DateUtil;
import com.red.star.wechat.data.utils.ExportUtil;
import com.red.star.wechat.work.constant.AdminSessionHolder;
import com.red.star.wechat.work.constant.Constant;
import com.red.star.wechat.work.entity.Admin;
import com.red.star.wechat.work.entity.TableContainer;
import com.red.star.wechat.work.utils.CommonUtil;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.thymeleaf.util.StringUtils;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.util.StringUtil;

import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
public class BannerService {

    @Resource
    private BannerMapper bannerMapper;

    @Resource
    private BannerMallMapper bannerMallMapper;

    @Resource
    private MallMapper mallMapper;

    public List<MallBanner> findBannerOrderByMallCode(String mallCode) {
        return bannerMapper.findBannerOrderByMallCode(mallCode);
    }

    public Banner findBannerByBannerId(Integer bannerId) {
        return bannerMapper.findBannerByBannerId(bannerId);
    }

    public List<Banner> findBannerByMallCode(String mallCode) {
        return bannerMapper.findBannerByMallCode(mallCode);
    }

    public List<Banner> findSortBannerByMallCode(String mallCode) {
        return bannerMapper.findSortBannerByMallCode(mallCode);
    }

    public TableContainer queryBannerData(MallBannerDataVo mallBannerDataVo) throws ParseException {
        Page<?> page = PageHelper.startPage(mallBannerDataVo.getPage(), mallBannerDataVo.getRows());
        String mallCode = null;
        String bannerId = null;
        String bannerName = null;
        String status = null;
        Date startTime = null;
        Date endTime = null;
        if (mallBannerDataVo != null) {
            bannerId = mallBannerDataVo.getBannerId();
            bannerName = mallBannerDataVo.getBannerName();
            mallCode = mallBannerDataVo.getMallCode();
            status = mallBannerDataVo.getStatus();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            if (!CheckUtil.isEmpty(mallBannerDataVo.getStartTime())) {
                startTime = sdf.parse(mallBannerDataVo.getStartTime());
            }
            if (!CheckUtil.isEmpty(mallBannerDataVo.getEndTime())) {
                endTime = sdf.parse(mallBannerDataVo.getEndTime());
                //结束时间加一天
                if (!CheckUtil.isEmpty(endTime)) {
                    Calendar calendar = new GregorianCalendar();
                    calendar.setTime(endTime);
                    calendar.add(calendar.DATE, 1);
                    endTime = calendar.getTime();
                }
            }
        }
        List<MallBannerDataVo> list = null;
        Admin admin = AdminSessionHolder.get();
        String userMallCode = admin.getMallCode();
        list = bannerMapper.queryBannerData(userMallCode, mallCode, bannerId, bannerName, status, startTime, endTime);
        List<MallBannerDataVo> list2 = new ArrayList<>();
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date endDate = null;
        for (MallBannerDataVo mallBannerDataVo2 : list) {
            endDate = sdf2.parse(mallBannerDataVo2.getEndTime());
            String status2 = mallBannerDataVo2.getStatus();
            if ("0".equals(status2)) {
                if (endDate.before(new Date())) {
                    mallBannerDataVo2.setStatus("已失效");
                } else {
                    mallBannerDataVo2.setStatus("待上架");
                }
            } else if ("1".equals(status2)) {
                if (endDate.before(new Date())) {
                    mallBannerDataVo2.setStatus("已失效");
                } else {
                    mallBannerDataVo2.setStatus("已上架");
                }
            } else if ("2".equals(status2)) {
                if (endDate.before(new Date())) {
                    mallBannerDataVo2.setStatus("已失效");
                } else {
                    mallBannerDataVo2.setStatus("已下架");
                }
            }
            String mallCode2 = mallBannerDataVo2.getMallCode();
            if (CheckUtil.isEmpty(mallCode2)) {
                mallBannerDataVo2.setMallName("集团");
            }
            list2.add(mallBannerDataVo2);
        }

        return CommonUtil.backTableContainer(list2, page);
    }


    public byte[] exploreBannerData(String bannerId, String bannerName, String status, String mallCode, Date startTime, Date endTime) throws ParseException {
        List<Map<String, Object>> exploreList = new ArrayList<>();
        List<MallBannerDataVo> list = null;
        Admin admin = AdminSessionHolder.get();
        String userMallCode = admin.getMallCode();
        list = bannerMapper.queryBannerData(userMallCode, mallCode, bannerId, bannerName, status, startTime, endTime);
        if (!CheckUtil.isEmpty(list)) {
            for (MallBannerDataVo mallBannerData : list) {
                Map<String, Object> userMap = new HashMap<>();
                userMap.put("bannerId", mallBannerData.getBannerId() == null ? "" : mallBannerData.getBannerId());
                userMap.put("bannerName", mallBannerData.getBannerName() == null ? "" : mallBannerData.getBannerName());
                String mallName2 = mallBannerData.getMallName() == null ? "" : mallBannerData.getMallName();
                if (CheckUtil.isEmpty(mallName2)) {
                    mallName2 = "集团";
                }
                userMap.put("mallName", mallName2);
                String sTime = mallBannerData.getStartTime() == null ? "" : mallBannerData.getStartTime();
                String eTime = mallBannerData.getEndTime() == null ? "" : mallBannerData.getEndTime();
                String statusName = mallBannerData.getStatus() == null ? "" : mallBannerData.getStatus();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date startDate = sdf.parse(sTime);
                Date endDate = sdf.parse(eTime);
                if (endDate.before(new Date())) {
                    statusName = "已失效";
                } else {
                    if ("0".equals(statusName)) {
                        statusName = "待上架";
                    } else if ("1".equals(statusName)) {
                        statusName = "已上架";
                    } else if ("2".equals(statusName)) {
                        statusName = "已下架";
                    }
                }
                userMap.put("status", statusName);
                if (!CheckUtil.isEmpty(startDate) && !CheckUtil.isEmpty(endDate)) {
                    sTime = new SimpleDateFormat("yyyy-MM-dd").format(startDate);
                    eTime = new SimpleDateFormat("yyyy-MM-dd").format(endDate);
                    userMap.put("bannerTime", sTime + " ~ " + eTime);
                }
                userMap.put("bannerPV", mallBannerData.getBannerPV() == null ? "" : mallBannerData.getBannerPV());
                userMap.put("bannerUV", mallBannerData.getBannerUV() == null ? "" : mallBannerData.getBannerUV());
                exploreList.add(userMap);
            }
        }
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        if (CheckUtil.isEmpty(mallCode)) {
            ExportUtil.doExport(exploreList, Constant.GROUP_DATA_COLUNM, Constant.BANNER_DATA_FIELD, os);
        } else {
            ExportUtil.doExport(exploreList, Constant.MALL_DATA_COLUNM, Constant.BANNER_DATA_FIELD, os);
        }
        return os.toByteArray();

    }


    /**
     * @Description: banner列表
     * @Author: liucancan
     * @Date: 2018/9/27
     */
    public TableContainer findBanner(BannerExpand bannerExpand) {
        Page<?> page = PageHelper.startPage(bannerExpand.getPage(), bannerExpand.getRows());
        List<BannerExpand> banner = bannerMapper.findBanner(bannerExpand);
        return CommonUtil.backTableContainer(banner, page);
    }

    /**
     * @Description: 新增banner
     * @Param: [bannerExpand]
     * @return: TableContainer
     * @Author: liucancan
     * @Date: 2018/9/29
     */
    @Transactional
    public ResponseEntity addBanner(BannerExpand bannerExpands) {
        // 添加banner
        bannerExpands.setCreateTime(new Date());
        bannerExpands.setUpdateTime(bannerExpands.getCreateTime());
        if (null != bannerExpands.getLinkType() && bannerExpands.getLinkType() == 1 && !StringUtil.isEmpty(bannerExpands.getLink())) {
            String[] split = bannerExpands.getLink().split(",");
            bannerExpands.setPosterId(Integer.parseInt(split[0]));
            bannerExpands.setPosterType(split[1]);
            bannerExpands.setPosterName(split[2]);
            bannerExpands.setLink("");
        }
        int insert = bannerMapper.insertBanner(bannerExpands);
        if (insert == 0) {
            throw new RuntimeException();
        }
        if (null != bannerExpands.getSorts() && null != bannerExpands.getMallCodes()) {
            List<BannerMall> bannerMalls = new ArrayList<>();
            for (int i = 0; i < bannerExpands.getSorts().size(); i++) {
                for (String mallCode : bannerExpands.getMallCodes().get(i)) {
                    BannerMall bannerMall = new BannerMall();
                    bannerMall.setBannerOrder(bannerExpands.getSorts().get(i));
                    bannerMall.setMallCode(mallCode);
                    bannerMall.setBannerId(bannerExpands.getId());
                    bannerMalls.add(bannerMall);
                }
            }
            int result = bannerMallMapper.insertList(bannerMalls);
            if (result == 0) {
                throw new RuntimeException();
            }
        }
        return new ResponseEntity(true, HttpStatus.OK);
    }

    /**
     * @Description: 修改banner状态
     * @Param: [bannerExpand]
     * @return: TableContainer
     * @Author: liucancan
     * @Date: 2018/9/29
     */
    @Transactional
    public ResponseEntity changeBannerStatus(BannerExpand bannerExpands) {
        if (bannerExpands.getStatus() == 1) {
            /**
             * 过滤集团重复下发banner给商场，出现重复下发时覆盖掉上一位置的banner
             * 将下发到该商城的相同位置的关联数据删除(t_banner_mall)
             */
            // 根据bannerid查询所有的bannerMall并根据sort分组
            List<BannerMall> bannerMalls = bannerMallMapper.findBannerMall(bannerExpands.getId());
            for (BannerMall bannerMall : bannerMalls) {
                bannerMallMapper.deleteBannerMallByMallCodeAndSort(bannerMall.getMallCode(), bannerMall.getBannerOrder(), bannerExpands.getId());
            }
        }
        int i = bannerMapper.updateByPrimaryKeySelective(bannerExpands);
        if (i > 0) {
            return new ResponseEntity(true, HttpStatus.OK);
        }
        return new ResponseEntity(false, HttpStatus.BAD_REQUEST);
    }

    /**
     * @Description: banner详情
     * @Param: [bannerExpand]
     * @return: TableContainer
     * @Author: liucancan
     * @Date: 2018/9/29
     */
    public ResponseEntity bannerInfo(BannerExpand bannerExpand) {
        Banner banner = bannerMapper.findBannerByBannerId(bannerExpand.getId());
        Map<String, Object> bannerMall = new HashMap<>();
        bannerMall.put("banner", banner);
        // 查询集团下发的商场
        Admin admin = AdminSessionHolder.get();
        if (StringUtils.isEmpty(admin.getMallCode())) {
            Example example = new Example(BannerMall.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("bannerId", bannerExpand.getId());
            List<BannerMall> bannerMalls = bannerMallMapper.selectByExample(example);
            Map<Integer, List<BannerMall>> collect = bannerMalls.stream().collect(Collectors.groupingBy(BannerMall::getBannerOrder));
            bannerMall.put("sortMall", collect);
        }
        return new ResponseEntity(bannerMall, HttpStatus.OK);
    }

    /**
     * @Description: banner下发商城
     * @Author: liucancan
     * @Date: 2018/9/29
     */
    public ResponseEntity sentDown(BannerExpand bannerExpand) {
        Example example = new Example(BannerMall.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("bannerId", bannerExpand.getId());
        bannerMallMapper.deleteByExample(example);
        // 查询banner状态
        Banner banner = bannerMapper.selectByPrimaryKey(bannerExpand.getId());
        boolean setUp = banner.getStatus() == 1 ? true : false;
        if (null != bannerExpand.getSorts() && null != bannerExpand.getMallCodes()) {
            List<BannerMall> bannerMalls = new ArrayList<>();
            for (int i = 0; i < bannerExpand.getSorts().size(); i++) {
                for (String mallCode : bannerExpand.getMallCodes().get(i)) {
                    BannerMall bannerMall = new BannerMall();
                    bannerMall.setBannerOrder(bannerExpand.getSorts().get(i));
                    bannerMall.setMallCode(mallCode);
                    bannerMall.setBannerId(bannerExpand.getId());
                    bannerMalls.add(bannerMall);
                    /**
                     * 过滤集团重复下发banner给商场，出现重复下发时覆盖掉上一位置的banner
                     * 将下发到该商城的相同位置的关联数据删除(t_banner_mall)
                     */
                    if (setUp) {
                        bannerMallMapper.deleteBannerMallByMallCodeAndSort(mallCode, bannerExpand.getSorts().get(i), bannerExpand.getId());
                    }
                }
            }
            int result = bannerMallMapper.insertList(bannerMalls);
            if (result == 0) {
                throw new RuntimeException();
            }
        }
        return new ResponseEntity(true, HttpStatus.OK);
    }

    /**
     * @Description: banner排序和上下架
     * @Author: lijing
     * @Date: 2018/10/8
     */
    public List<MallBannerDataVo> selectWorkableBanner(String mallCode) {
        List<MallBannerDataVo> bannerList = bannerMapper.selectWorkableBanner(mallCode);
        return bannerList;
    }

    /**
     * @Description: banner上架
     * @Author: lijing
     * @Date: 2018/10/8
     */
    public void putawayBannerStatus(List<Banner> bannerList) {
        for (Banner banner : bannerList) {
            String bannerId = banner.getId() + "";
            Integer sort = banner.getSort();
            if (!CheckUtil.isEmpty(bannerId)) {
                bannerMapper.putawayBannerStatus(bannerId, sort);
            }
        }
    }

    /**
     * @Description: banner上架
     * @Author: lijing
     * @Date: 2018/10/8
     */
    public void removeBannerStatus(String bannerId) {
        bannerMapper.removeBannerStatus(bannerId);
    }

    /**
     * @Description: banner排序展示
     * @Author: lijing
     * @Date: 2018/10/8
     */
    public List<MallBannerDataVo> selectValidBanner(String mallCode) {
        List<MallBannerDataVo> bannerList = bannerMapper.selectValidBanner(mallCode);
        return bannerList;
    }

    public List<Mall> selectAllMall(String mallCode) {
        return bannerMapper.selectMallByMallCode(mallCode);
    }

    /**
     * @Description: 编辑banner
     * @Param: [bannerExpand]
     * @return: void
     * @Author: liucancan
     * @Date: 2018/10/31
     */
    @Transactional
    public ResponseEntity editBanner(BannerExpand bannerExpand) {
        // 更新banner操作
        Banner banner = bannerMapper.selectByPrimaryKey(bannerExpand);
        bannerExpand.setCreateTime(banner.getCreateTime());
        Admin admin = AdminSessionHolder.get();
        bannerExpand.setMallCode(admin.getMallCode());
        bannerExpand.setStatus(banner.getStatus());
        bannerExpand.setSort(banner.getSort());
        if (!CheckUtil.isEmpty(bannerExpand.getBannerStartTime())) {
            bannerExpand.setStartTime(DateUtil.getDateAsYYYYMMDD(bannerExpand.getBannerStartTime()));
        }
        if (!CheckUtil.isEmpty(bannerExpand.getBannerEndTime())) {
            Date endTime = DateUtil.getDateAsYYYYMMDD(bannerExpand.getBannerEndTime());
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(endTime);
            calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
                    calendar.get(Calendar.DAY_OF_MONTH),
                    23, 59, 59);
            bannerExpand.setEndTime(calendar.getTime());
        }
        // 微信H5链接时判断是否可用
        if (null != bannerExpand.getLinkType() && 2 == bannerExpand.getLinkType()) {
            String url = bannerExpand.getLink();
            url = ((url.substring(0, 7).toLowerCase().equals("http://")) ? url.replace("http://", "https://") : ((url.substring(0, 8).toLowerCase().equals("https://"))) ? url : "https://" + url);
            bannerExpand.setLink(url);
            String[] h5urls = SysParam.MINI_PROGRAM_H5_URL.split(",");
            Matcher matcherOne = Pattern.compile("^([hH][tT]{2}[pP]://|[hH][tT]{2}[pP][sS]://)(([A-Za-z0-9-~]+).)+([A-Za-z0-9-~\\/])+$").matcher(bannerExpand.getLink());
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("msg", "H5链接不可用,");
            if (matcherOne.find()) {
                Matcher matcherTwo = Pattern.compile("[^//]*?\\.(com|cn|net|org|biz|info|cc|tv)").matcher(bannerExpand.getLink());
                boolean contains;
                if (matcherTwo.find()) {
                    contains = Arrays.asList(h5urls).contains(matcherTwo.group());
                    if (!contains) {
                        return new ResponseEntity(resultMap, HttpStatus.OK);
                    }
                } else {
                    return new ResponseEntity(resultMap, HttpStatus.OK);
                }
            } else {
                return new ResponseEntity(resultMap, HttpStatus.OK);
            }
        }
        // 对应连接为电子海报时
        if (null != bannerExpand.getLinkType() && bannerExpand.getLinkType() == 1 && !StringUtil.isEmpty(bannerExpand.getLink())) {
            String[] split = bannerExpand.getLink().split(",");
            bannerExpand.setPosterId(Integer.parseInt(split[0]));
            bannerExpand.setPosterType(split[1]);
            bannerExpand.setPosterName(split[2]);
            bannerExpand.setLink("");
        }
        bannerExpand.setUpdateTime(new Date());
        bannerExpand.setStatus(0);
        bannerMapper.updateByPrimaryKey(bannerExpand);
        // 集团修改时需下发商场
        if (StringUtils.isEmpty(admin.getMallCode())) {
            ResponseEntity responseEntity = sentDown(bannerExpand);
            if (responseEntity.getStatusCodeValue() != 200) {
                new RuntimeException();
            }
        }
        return new ResponseEntity(true, HttpStatus.OK);
    }
}
